#!/usr/bin/env python3
"""
CR正负号功能部署脚本
适用于在其他环境中快速部署CR正负号修改
"""
import os
import sys
import shutil
from pathlib import Path

def apply_cr_sign_fixes():
    """应用CR正负号修改"""
    print("=== 开始应用CR正负号修改 ===")
    
    # 检查必要文件是否存在
    required_files = [
        'src/storage/sqlalchemy_storage.py',
        'src/core/trade_processor.py'
    ]
    
    for file_path in required_files:
        if not os.path.exists(file_path):
            print(f"❌ 找不到必要文件: {file_path}")
            return False
    
    print("✅ 所有必要文件都存在")
    
    # 备份原始文件
    backup_dir = 'backup_before_cr_fix'
    if not os.path.exists(backup_dir):
        os.makedirs(backup_dir)
    
    for file_path in required_files:
        backup_path = os.path.join(backup_dir, os.path.basename(file_path))
        shutil.copy2(file_path, backup_path)
        print(f"📁 备份文件: {file_path} → {backup_path}")
    
    # 修改 sqlalchemy_storage.py
    success1 = modify_sqlalchemy_storage()
    
    # 修改 trade_processor.py  
    success2 = modify_trade_processor()
    
    if success1 and success2:
        print("✅ 所有文件修改完成")
        return True
    else:
        print("❌ 部分文件修改失败")
        return False

def modify_sqlalchemy_storage():
    """修改 sqlalchemy_storage.py 中的CR计算逻辑"""
    file_path = 'src/storage/sqlalchemy_storage.py'
    print(f"\n🔧 修改文件: {file_path}")
    
    try:
        with open(file_path, 'r', encoding='utf-8') as f:
            content = f.read()
        
        # 查找并替换CR计算相关代码
        old_comment = "# 计算CloseRRR: 实际盈亏点数的绝对值/止损距离"
        new_comment = "# 计算CloseRRR: 实际盈亏点数/止损距离 (保持正负号)"
        
        old_logic = "# 使用实际盈亏点数的绝对值与止损距离的比值\n                actual_points = abs(trade.point_profit_per_lot)"
        new_logic = "# 使用实际盈亏点数（保持正负号）与止损距离的比值\n                actual_points = trade.point_profit_per_lot  # 保持原始正负号"
        
        # 执行替换
        if old_comment in content:
            content = content.replace(old_comment, new_comment)
            print("  ✅ 更新了注释")
        else:
            print("  ⚠️  未找到预期的注释，可能已经修改过")
        
        if old_logic in content:
            content = content.replace(old_logic, new_logic)
            print("  ✅ 更新了计算逻辑")
        else:
            print("  ⚠️  未找到预期的计算逻辑，可能已经修改过")
        
        # 写回文件
        with open(file_path, 'w', encoding='utf-8') as f:
            f.write(content)
        
        print(f"  ✅ {file_path} 修改完成")
        return True
        
    except Exception as e:
        print(f"  ❌ 修改 {file_path} 时出错: {e}")
        return False

def modify_trade_processor():
    """修改 trade_processor.py 中的CR计算逻辑"""
    file_path = 'src/core/trade_processor.py'
    print(f"\n🔧 修改文件: {file_path}")
    
    try:
        with open(file_path, 'r', encoding='utf-8') as f:
            content = f.read()
        
        # 查找并替换函数注释
        old_docstring = "CloseRRR (CR) = 实际盈亏点数绝对值/止损距离"
        new_docstring = "CloseRRR (CR) = 实际盈亏点数/止损距离 (保持正负号)"
        
        # 查找并替换CR计算相关代码
        old_comment = "# 计算CloseRRR: 实际盈亏点数的绝对值/止损距离"
        new_comment = "# 计算CloseRRR: 实际盈亏点数/止损距离 (保持正负号)"
        
        old_logic = "# 使用实际盈亏点数的绝对值与止损距离的比值\n                actual_points = abs(trade.point_profit_per_lot)"
        new_logic = "# 使用实际盈亏点数（保持正负号）与止损距离的比值\n                actual_points = trade.point_profit_per_lot  # 保持原始正负号"
        
        # 执行替换
        if old_docstring in content:
            content = content.replace(old_docstring, new_docstring)
            print("  ✅ 更新了函数文档字符串")
        else:
            print("  ⚠️  未找到预期的函数文档字符串，可能已经修改过")
        
        if old_comment in content:
            content = content.replace(old_comment, new_comment)
            print("  ✅ 更新了注释")
        else:
            print("  ⚠️  未找到预期的注释，可能已经修改过")
        
        if old_logic in content:
            content = content.replace(old_logic, new_logic)
            print("  ✅ 更新了计算逻辑")
        else:
            print("  ⚠️  未找到预期的计算逻辑，可能已经修改过")
        
        # 写回文件
        with open(file_path, 'w', encoding='utf-8') as f:
            f.write(content)
        
        print(f"  ✅ {file_path} 修改完成")
        return True
        
    except Exception as e:
        print(f"  ❌ 修改 {file_path} 时出错: {e}")
        return False

def update_historical_data():
    """更新历史数据的CR值"""
    print(f"\n📊 开始更新历史数据的CR值...")
    
    try:
        # 检查是否有必要的依赖
        sys.path.append('src')
        
        from storage.sqlalchemy_storage import SQLAlchemyStorage
        from core.models import Trade
        
        # 尝试找到数据库路径
        possible_db_paths = [
            'db/trades.db',
            'trades.db',
            'data/trades.db'
        ]
        
        db_path = None
        for path in possible_db_paths:
            if os.path.exists(path):
                db_path = path
                break
        
        if not db_path:
            print("  ⚠️  未找到数据库文件，跳过历史数据更新")
            print("  💡 请手动运行历史数据更新脚本")
            return True
        
        print(f"  📁 找到数据库: {db_path}")
        
        # 连接数据库并更新
        storage = SQLAlchemyStorage(db_path)
        session = storage._get_session()
        
        try:
            trades_with_cr = session.query(Trade).filter(
                Trade.close_rrr.isnot(None),
                Trade.point_profit_per_lot.isnot(None),
                Trade.stop_loss_price.isnot(None)
            ).all()
            
            print(f"  📊 找到 {len(trades_with_cr)} 条有CR值的交易记录")
            
            updated_count = 0
            for trade in trades_with_cr:
                actual_points = trade.point_profit_per_lot
                stop_loss_distance = abs(trade.stop_loss_price)
                
                if stop_loss_distance > 0:
                    new_cr = round(actual_points / stop_loss_distance, 2)
                    old_cr = trade.close_rrr
                    
                    # 检查是否需要更新（如果现在是正值但应该是负值）
                    if (actual_points < 0 and old_cr > 0) or abs(old_cr - new_cr) > 0.01:
                        trade.close_rrr = new_cr
                        updated_count += 1
            
            session.commit()
            print(f"  ✅ 更新了 {updated_count} 条记录的CR值")
            
            # 统计结果
            positive_cr = session.query(Trade).filter(Trade.close_rrr > 0).count()
            negative_cr = session.query(Trade).filter(Trade.close_rrr < 0).count()
            zero_cr = session.query(Trade).filter(Trade.close_rrr == 0).count()
            
            print(f"  📊 CR值分布: 正值 {positive_cr}, 负值 {negative_cr}, 零值 {zero_cr}")
            
        finally:
            session.close()
        
        return True
        
    except Exception as e:
        print(f"  ❌ 更新历史数据时出错: {e}")
        print(f"  💡 请手动运行历史数据更新")
        return False

def create_manual_update_script():
    """创建手动更新历史数据的脚本"""
    script_content = '''#!/usr/bin/env python3
"""
手动更新历史数据CR值脚本
如果自动更新失败，请运行此脚本
"""
import sys
import os
sys.path.append('src')

from storage.sqlalchemy_storage import SQLAlchemyStorage
from core.models import Trade

def main():
    # 修改这里的数据库路径
    db_path = 'db/trades.db'  # 根据实际情况修改
    
    print("=== 更新历史数据CR值 ===")
    
    storage = SQLAlchemyStorage(db_path)
    session = storage._get_session()
    
    try:
        trades_with_cr = session.query(Trade).filter(
            Trade.close_rrr.isnot(None),
            Trade.point_profit_per_lot.isnot(None),
            Trade.stop_loss_price.isnot(None)
        ).all()
        
        print(f"找到 {len(trades_with_cr)} 条有CR值的交易记录")
        
        updated_count = 0
        for trade in trades_with_cr:
            actual_points = trade.point_profit_per_lot
            stop_loss_distance = abs(trade.stop_loss_price)
            
            if stop_loss_distance > 0:
                new_cr = round(actual_points / stop_loss_distance, 2)
                old_cr = trade.close_rrr
                
                if abs(old_cr - new_cr) > 0.01:
                    trade.close_rrr = new_cr
                    updated_count += 1
                    print(f"更新交易 {trade.trade_id[:10]}... CR: {old_cr} → {new_cr}")
        
        session.commit()
        print(f"更新完成！共更新 {updated_count} 条记录")
        
    finally:
        session.close()

if __name__ == "__main__":
    main()
'''
    
    with open('manual_update_cr.py', 'w', encoding='utf-8') as f:
        f.write(script_content)
    
    print("📝 已创建手动更新脚本: manual_update_cr.py")

def main():
    """主函数"""
    print("🚀 CR正负号功能部署脚本")
    print("=" * 50)
    
    # 检查当前目录是否是项目根目录
    if not os.path.exists('src/storage/sqlalchemy_storage.py'):
        print("❌ 请在项目根目录下运行此脚本")
        sys.exit(1)
    
    # 应用代码修改
    if not apply_cr_sign_fixes():
        print("❌ 代码修改失败")
        sys.exit(1)
    
    # 更新历史数据
    update_historical_data()
    
    # 创建手动更新脚本
    create_manual_update_script()
    
    print("\n" + "=" * 50)
    print("🎉 CR正负号功能部署完成！")
    print("\n📋 完成的工作:")
    print("  ✅ 修改了 sqlalchemy_storage.py 中的CR计算逻辑")
    print("  ✅ 修改了 trade_processor.py 中的CR计算逻辑") 
    print("  ✅ 尝试更新了历史数据的CR值")
    print("  ✅ 创建了手动更新脚本 manual_update_cr.py")
    print("\n💡 如果历史数据更新失败，请:")
    print("  1. 检查数据库路径是否正确")
    print("  2. 运行 python manual_update_cr.py")
    print("\n🔄 重启应用以使更改生效")

if __name__ == "__main__":
    main() 